package com.example.roomwordsample.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.example.roomwordsample.model.Word
import com.example.roomwordsample.repository.WordRepository
import kotlinx.coroutines.launch

class WordViewModel(private val repository: WordRepository) : ViewModel() {

    var items = repository.allWords.asLiveData()
        private set

    fun insert(word: Word) = viewModelScope.launch {
        repository.insert(word = word)
    }

    fun delete(id: Int) = viewModelScope.launch {
        repository.deleteById(id = id)
    }


    class WordViewModelFactory(private val repository: WordRepository) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(WordViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return WordViewModel(repository = repository) as T
            }
            throw IllegalArgumentException("Unknown ViewModel class")
        }
    }
}